package com.coisini.service.impl;

import com.coisini.dto.GoodsSalesDTO;
import com.coisini.entity.Orders;
import com.coisini.mapper.OrderMapper;
import com.coisini.mapper.UserMapper;
import com.coisini.service.ReportService;
import com.coisini.service.WorkspaceService;
import com.coisini.vo.*;
import io.lettuce.core.ScriptOutputType;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.conn.util.InetAddressUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 获取指定范围内的日期
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDate(LocalDate begin,LocalDate end){
        //集合用来存储范围内的日期
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (! begin.equals(end)){
            begin=begin.plusDays(1); //指定日期的后一天
            dateList.add(begin);
        }
        return dateList;
    }


    /**
     * 1.动态查询日期范围内的营业额
     * 先获取范围内的每一天的日期
     * 对每一天的订单进行查询，统计当天已完成订单的金额
     * 将两个集合日期集合，营业额集合转为字符串并用，隔开，实现一一对应
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        //1.先获取范围内的每一天的日期
        List<LocalDate> dateList = getDate(begin, end);

        //2.获取每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //需要将LocalDate类型的日期转为LocalDateTime类型的
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //map集合用来存储查询的条件
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin",beginTime);
            map.put("end", endTime);

            //当天的营业额
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover; //当天没有营业额用0.0表示
            turnoverList.add(turnover);
        }

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))  // 将集合转为字符串类型，中间用逗号隔开
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     *2.根据日期统计订单
     * 有效订单指状态为 “已完成” 的订单
     * 展示每天的订单总数和有效订单数
     * 订单完成率 = 有效订单数 / 总订单数 * 100%
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //1.先获取范围内的每一天的日期
        List<LocalDate> dateList = getDate(begin, end);

        //定义集合表示总订单数
        List<Integer> orderCountList=new ArrayList<>();
        //定义集合表示有效订单数
        List<Integer> validOrderCountList=new ArrayList<>();

        //2.遍历日期集合，根据日期查询当天的订单
        for (LocalDate date : dateList) {
            //需要将LocalDate类型的日期转为LocalDateTime类型的
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //根据日期查询当天总的订单数
            //select count(id) from orders where order_time > ? and order_time < ?
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            orderCountList.add(orderCount);
            //根据日期及订单状态查询有效订单
            //elect count(id) from orders where order_time > ? and order_time < ? and status = ?
            Integer count = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            validOrderCountList.add(count);
        }
        //时间范围内的订单总数及有效订单数
        Integer totalOrderCount = getOrderCount(null, LocalDateTime.of(end, LocalTime.MAX), null);
        Integer validOrderCount = getOrderCount(null, LocalDateTime.of(end, LocalTime.MAX), Orders.COMPLETED);
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }
    /**
     * 根据时间区间统计指定状态的订单数量
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("status", status);
        map.put("begin",beginTime);
        map.put("end", endTime);
        return orderMapper.countByMap(map);
    }

    /**
     * 3.用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1.先获取范围内的每一天的日期
        List<LocalDate> dateList = getDate(begin, end);

        //定义集合用来表示新增，总用户数据
        List<Integer> totalUserList=new ArrayList<>(); //总用户数据
        List<Integer> newUserList=new ArrayList<>(); //新增用户数据

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //新增用户数量 select count(id) from user where create_time > ? and create_time < ?
            Integer count = getUserCount(beginTime, endTime);
            newUserList.add(count);
            //总用户数量 select count(id) from user where  create_time < ?
            Integer userCount = getUserCount(null, endTime);
            totalUserList.add(userCount);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }
    /**
     * 根据时间区间统计用户数量
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end", endTime);
        return userMapper.countByMap(map);
    }

    /**
     * 4.查询销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //根据时间及订单状态查询订单
        //订单状态为已完成
       List<GoodsSalesDTO> goodsSalesDTOList= orderMapper.getTop10(beginTime,endTime,Orders.COMPLETED);
//        System.out.println(goodsSalesDTOList);
        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 5.导出excel报表
     * 查询数据 近30天的数据
     * 通过poi将数据写入excel文件中
     * 通过输出流将excel文件响应给浏览器
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        //1.获取近30天的营业数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //2.通过poi向excel文件中写入数据
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //数据概览
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //数据明细
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
